const Controller = require('egg').Controller;
const wechat = require('co-wechat')

class WxController extends Controller {
  async verify() {
    const { ctx } = this;
    ctx.body = await ctx.service.wx.verify();
  }
}

WxController.prototype.wechat = wechat({
  token: 'linhuibin98',
  appid: 'wxdd0b9073b89ca26d',
  encodingAESKey: ''
}).middleware(async (message, ctx) => {
  console.log('收到微信消息====', message);
  let msg = '您好';
  if (message.MsgType === 'text') {
    const recived = message.Content;
    const resp = await ctx.curl(`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${recived}`);
    let data = resp.data.toString();
    data = JSON.parse(data);
    if (data.result === 0) {
      msg = data.content;
    }
    return msg;
  } else if (message.MsgType === 'event' && message.Event === 'LOCATION') {
    return 'Hi, 有什么可以帮助您的吗？';
  }
  return '无法读取该消息';
});

module.exports = WxController;